#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include "logfile.h"

static FILE *logfilefp;
char _logfilename[1024];

void
debug_open_log (void)
{
	char *p;

	if (logfilefp != NULL)
	{
		debug_log ("already open logfile\n");
		return;
	}

	if (!strlen(_logfilename))
	{
		time_t curtime;
		curtime = time (0);
		strftime(_logfilename,1023,DEFAULTLOGFILENAME,localtime(&curtime));
		//strncpy (_logfilename, DEFAULTLOGFILENAME, 1023);
	}
	p = _logfilename;

	while (*p == ' ')
		p++;
	if ((logfilefp = fopen (p, "a")) == NULL)
		{
			debug_log ("open normal logfile:[%s][%s] error!\n",
				   _logfilename, p);
		}
	return;
}

char *
debug_log_timestamp (void)
{
	time_t t;
	int sz;
	char *tmp_str;

	t = time (NULL);

	if (t == (time_t) - 1)
		return NULL;

	tmp_str = ctime (&t);
	sz = strlen (tmp_str);
	/* chop off the \n */
	tmp_str[sz - 1] = '\0';

	return tmp_str;
}

void
debug_log (const char *msgfmt, ...)
{
	va_list ap;
	char message[MAX_LOG_SIZE];
	char *pos;
	int offset;

	snprintf (message, MAX_LOG_SIZE, "[%s] ", debug_log_timestamp ());
	for (pos = message; *pos != '\0'; pos++);	//empty statement

	offset = pos - message;

	va_start (ap, msgfmt);
	vsnprintf (pos, MAX_LOG_SIZE - offset, msgfmt, ap);
	if (logfilefp == NULL)
	{
		debug_open_log ();
	}
	if (logfilefp == NULL)
	{
		fprintf (stdout, "%s", message);
		if (message[strlen (message) - 1] != '\n')
		{
			fprintf (stdout, "\n");
		}
		fflush (stdout);
	}
	else
	{
		fprintf (logfilefp, "%s", message);
#ifdef DEBUG_LOG_STDOUT
			fprintf (stdout,"%s",message);
#endif
		if (message[strlen (message) - 1] != '\n')
		{
			fprintf (logfilefp, "\n");
#ifdef DEBUG_LOG_STDOUT
			fprintf (stdout,"\n");
#endif
		}
		fflush (logfilefp);
#ifdef DEBUG_LOG_STDOUT
		fflush(stdout);
#endif
	}
}
